'use strict';
/**
 * Created by FreezeSoul on 2015/10/10.
 */
define([
    'angular',
    'adConfig',
    'app/modules/index/define',
    'app/modules/index/controllers/index-add',
    'app/modules/index/controllers/index-delete',
    'app/modules/index/services/index',
    'app/modules/folder/controllers/folder',
    'app/modules/folder/services/folder-tree'
], function (angular, adConfig) {
    angular.module('ad.index')
        .controller('adIndexTreeController', ['$rootScope', '$scope', '$state', '$stateParams', '$uibModal', '_', 'Notification', 'adFolderEditService', 'adIndexEditService'
            , function ($rootScope, $scope, $state, $statePara, $uibModal, _, Notification, folderService, chartsService) {

                $scope.isTreeLoading = true;

                $scope.treeOptions = {
                    nodeChildren: "children",
                    dirSelectable: false,
                    allowDeselect: false,
                    isSelectable: function (node) {
                        return node.type !== "folder";
                    },
                    injectClasses: {
                        "iExpanded": "glyphicon glyphicon-chevron-down",
                        "iCollapsed": "glyphicon glyphicon-chevron-right"
                    }
                };

                $scope.treeModels = [];

                $scope.expandedFolders = [];

                $scope.selected = undefined;

                $scope.itemSelected = function (node) {
                    $state.go('editor.index-edit', {chartid: node.id});
                };

                $scope.addFolder = function ($event, node) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: 'app/modules/folder/views/folder-name.tpl.html',
                        controller: 'adFolderEditController',
                        size: 'lg',
                        resolve: {
                            item: function () {
                                return node;
                            },
                            type: function () {
                                return adConfig.chartFolderType;
                            },
                            action: function () {
                                return 'folderAdd';
                            }
                        }
                    });

                    modalInstance.result.then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var folder = {
                                "name": obj.data.folder_name,
                                "id": obj.data.folder_id,
                                "type": "folder",
                                "data": obj.data,
                                "children": [],
                                "parent": node
                            };
                            var lastIndex = _.findLastIndex(node.children, function (item) {
                                return item.type == "folder";
                            });
                            lastIndex = lastIndex == -1 ? 0 : lastIndex + 1;
                            node.children.splice(lastIndex, 0, folder);
                            if ($scope.expandedFolders.indexOf(node) == -1) {
                                $scope.expandedFolders.push(node);
                            }
                            Notification.success('添加成功！');
                        }
                    }, function () {
                    });
                    fixCloseMenu($event);
                };

                $scope.updateFolder = function ($event, node) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: 'app/modules/folder/views/folder-name.tpl.html',
                        controller: 'adFolderEditController',
                        size: 'lg',
                        resolve: {
                            item: function () {
                                return node;
                            },
                            type: function () {
                                return adConfig.chartFolderType;
                            },
                            action: function () {
                                return 'folderUpdate';
                            }
                        }
                    });

                    modalInstance.result.then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            node.data = obj.data;
                            node.name = obj.data.folder_name;
                            Notification.success('修改成功！');
                        }
                    }, function () {
                    });
                    fixCloseMenu($event);
                };


                $scope.removeFolder = function ($event, node) {
                    if (node.type == "folder" && node.id == adConfig.rootFolderId)
                        return;

                    var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: 'app/modules/folder/views/folder-delete.tpl.html',
                        controller: 'adFolderDeleteController',
                        size: 'sm',
                        resolve: {
                            item: function () {
                                return node;
                            },
                            type: function () {
                                return adConfig.chartFolderType;
                            }
                        }
                    });

                    modalInstance.result.then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var index = node.parent.children.indexOf(node);
                            if (index > -1) {
                                node.parent.children.splice(index, 1);
                            }
                            Notification.success('删除成功！');
                        }
                    }, function () {
                    });
                    fixCloseMenu($event);
                };

                $scope.addChart = function ($event, node) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: 'app/modules/index/views/index-add.tpl.html',
                        controller: 'adIndexAddController',
                        size: 'lg',
                        resolve: {
                            item: function () {
                                return node;
                            }
                        }
                    });

                    modalInstance.result.then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var chart = {
                                "name": obj.data.chart_name,
                                "id": obj.data.chart_id,
                                "type": "element",
                                "data": obj.data,
                                "children": [],
                                "parent": node
                            };
                            node.children.push(chart);
                            if ($scope.expandedFolders.indexOf(node) == -1) {
                                $scope.expandedFolders.push(node);
                            }
                            $scope.selected = chart;
                            $scope.itemSelected(chart);
                            Notification.success('添加成功！');
                        }
                    }, function () {
                    });
                    fixCloseMenu($event);
                };

                $scope.updateChart = function ($event, node) {
                    $state.go('editor.index-edit', {chartid: node.id});
                };

                $scope.removeChart = function ($event, node) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        templateUrl: 'app/modules/index/views/index-delete.tpl.html',
                        controller: 'adIndexDeleteController',
                        size: 'sm',
                        resolve: {
                            items: function () {
                                return [node.data];
                            }
                        }
                    });

                    modalInstance.result.then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var index = node.parent.children.indexOf(node);
                            if (index > -1) {
                                node.parent.children.splice(index, 1);
                            }
                            Notification.success('删除成功！');
                            if ($state.$current.name == 'editor.index.search') {
                                $state.reload();
                            } else {
                                $state.go("editor.index.search")
                            }
                        }
                    }, function () {
                    });
                    fixCloseMenu($event);
                };

                $scope.loadFolders = function () {
                    folderService.getFolders(adConfig.chartFolderType).then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var rootItemId = adConfig.rootFolderId;
                            var rootItem = {
                                "name": "指标根目录",
                                "id": rootItemId,
                                "type": "folder",
                                "data": {folder_id: rootItemId},
                                "children": [],
                                "parent": {}
                            };
                            $scope.expandedFolders.push(rootItem);
                            var convertFolderToTreeNode = function (currentParentId, parentFolderItem) {
                                var folders = _.filter(obj.data, function (item) {
                                    return item.folder_parent == currentParentId
                                });
                                folders = _.sortBy(folders, function (item) {
                                    return item.folder_name
                                });
                                _.each(folders, function (folder) {
                                    var currentId = folder.folder_id;
                                    var currentItem = {
                                        "name": folder.folder_name,
                                        "id": folder.folder_id,
                                        "type": "folder",
                                        "data": folder,
                                        "children": [],
                                        "parent": parentFolderItem
                                    };
                                    convertFolderToTreeNode(currentId, currentItem);
                                    parentFolderItem.children.push(currentItem);
                                })
                            };
                            convertFolderToTreeNode(rootItemId, rootItem);

                            $scope.loadCharts(rootItem);
                        }
                    }, function () {
                    });
                };

                $scope.loadCharts = function (rootItem) {
                    chartsService.getCharts().then(function (data) {
                        var obj = angular.fromJson(data);
                        if (obj.result == 'success') {
                            var walkThroughFolders = function (folder) {
                                var folderId = folder.id;
                                var charts = _.filter(obj.data, function (item) {
                                    return item.chart_folder_id == folderId
                                });
                                charts = _.sortBy(charts, function (chart) {
                                    return chart.chart_name;
                                });
                                _.each(charts, function (chart) {
                                    var item = {
                                        "name": chart.chart_name,
                                        "tooltip": chart.chart_type_id,
                                        "id": chart.chart_id,
                                        "type": "element",
                                        "data": chart,
                                        "children": [],
                                        "parent": folder
                                    };
                                    folder.children.push(item);
                                });
                                var childFolders = _.filter(folder.children, function (item) {
                                    return item.type == "folder"
                                });
                                _.each(childFolders, function (folder) {
                                    walkThroughFolders(folder);
                                })
                            };
                            walkThroughFolders(rootItem);

                            $scope.treeModels.push(rootItem);

                            $scope.isTreeLoading = false;
                        }
                    });
                };

                //Fix Tree With ContextMenu Bug
                function fixCloseMenu($event) {
                    $event.stopPropagation();
                    var target = $event.currentTarget || $event.srcElement;
                    var ulEl = angular.element(target).parent();
                    ulEl.parent().removeClass("open");
                }

                $scope.loadFolders();
            }]);
});